//
//  SingleMonthView.m
//  YWCalendar
//
//  Created by YR on 2017/5/25.
//  Copyright © 2017年 YR. All rights reserved.
//

#import "YWSingleMonthView.h"

#import "NSCalendar+YWDateConvertor.h"

@interface YWSingleMonthView ()

@end

@implementation YWSingleMonthView

- (instancetype)initWithYear:(NSInteger)year andMonth:(NSInteger)month {
    self = [super init];
    if (self) {
        //  根据年月 获取需显示的月信息对应的YWSingleMonthModel
        _model = [[YWSingleMonthModel alloc] initWithYear:year month:month];
        [self initBtn];
    }
    return self;
}

- (void)initBtn {
    // 确定横坐标开始位置和间距，将设置每个按钮位置，摆放按钮
    CGFloat spanX = 0;
    CGFloat viewWidth = self.bounds.size.width;
    spanX = (viewWidth - 7 * 60) / 7;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    for (int i = 0; i < 7 *  kRows; i++) {
        YWButton *button = [YWButton buttonWithType:UIButtonTypeCustom];
        //获取按钮对应的日期信息 .dayDate在按钮类中实现其set方法设置button的title
        button.dayDate = [calendar yw_dateFromDate:_model.calendarStartDayDate withDayOffset:i];
        [self addSubview:button];
        [button addTarget:self
                   action:@selector(dayButtonClicked:)
         forControlEvents:UIControlEventTouchUpInside];

        button.frame = CGRectMake( (i%7) * (375/7) , 10 + (i / 7) * (55 + -3),(375/7),55);
       
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];

        //  计算按钮日期和今天相差的天数（默认今天被选中）
        NSInteger diff = [calendar yw_dayIntervalFromDate:[calendar yw_dayStartDateForDate: [calendar yw_dateFromDate:_model.calendarStartDayDate withDayOffset:i]] toDate:[calendar yw_dayStartDateForDate:[NSDate date]]];
            button.didSelected = (diff == 0?YES:NO);
        if (diff == 0) {
            _didSelectButn = button;
        }
    }
}

#pragma mark - event
- (void)dayButtonClicked:(YWButton *)clickedButton {
    [self.delegate didSelectButton:clickedButton];
}


@end
